// Copyright (c) 2006 Zorm
// Released under the MIT License

#include "PCH.h"
#include "..\Common.h"

bool GLContext::Init() {
	
	m_windowDC = GetDC(m_windowHWND);
	PIXELFORMATDESCRIPTOR pfd;
	ZeroMemory(&pfd, sizeof(pfd));
	pfd.nSize = sizeof(pfd);
	pfd.nVersion = 1;
	pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
	pfd.cColorBits = 24;
	pfd.cDepthBits = 16;
	int format;
	if (!(format = ChoosePixelFormat(m_windowDC, &pfd))) {
		return false;
	}
	
	if (!SetPixelFormat(m_windowDC, format, &pfd)) {
		return false;
	}

	if (!(m_windowRC = wglCreateContext(m_windowDC))) {
		return false;
	}
	
	if (!wglMakeCurrent(m_windowDC, m_windowRC)) {
		return false;
	}
	
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	glShadeModel(GL_FLAT);

	glEnable(GL_POLYGON_OFFSET_FILL);
	glPolygonOffset(0.0, 1.0);

	glDisable(GL_NORMALIZE);
	glDisable(GL_BLEND);
	glDisable(GL_DEPTH_TEST);
	
	m_fontBase = glGenLists(96);
	HFONT font, oldFont;
	font = CreateFont(-13, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_TT_PRECIS,
			CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, FF_DONTCARE|DEFAULT_PITCH, "Tahoma");
	oldFont = (HFONT)SelectObject(m_windowDC, font);
	wglUseFontBitmaps(m_windowDC, 32, 96, m_fontBase);
	SelectObject(m_windowDC, oldFont);
	DeleteObject(font);
	
	return true;
}

void GLContext::Swap() {
	SwapBuffers(m_windowDC);
}

void GLContext::Resize(int width, int height) {
	ATH::Instance()->GetRadarInfo()->SetCenterX(width/2);
	ATH::Instance()->GetRadarInfo()->SetCenterY(height/2);
	glViewport(0, 0, width, height);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, width, 0, height, 1.0, -1.0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glTranslatef(0.375, 0.375, 0);
}

void GLContext::DrawString(int latitude, int longitude, char *text) {
	glRasterPos2i(latitude, longitude - 10);
	glPushAttrib(GL_LIST_BIT);
		glListBase(m_fontBase - 32);
		glCallLists(strlen((char *)text), GL_UNSIGNED_BYTE, text);
	glPopAttrib();
}